﻿using System;
using System.ComponentModel;
using System.IO;
using HAF.LogUtility;
using ICSharpCode.SharpZipLib.Tar;
using ICSharpCode.SharpZipLib.Zip;

namespace Iptv.ResourceDowner.Helper
{
    /// <summary>
    /// 文件压缩类
    /// </summary>
    [DisplayName("文件加解压帮助类")]
    public class ZipHelper
    {
        /// <summary>
        /// 解压资源文件
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="fileToUnZip">被解压文件</param>
        /// <param name="strUnpackDir">解压到指定文件夹</param>
        /// <param name="password">解压密码</param>
        /// <param name="allowPackDirectory">使用压缩包名做目录</param>
        [DisplayName("解压资源文件")]
        public static void UnZip(string taskId, string fileToUnZip, string strUnpackDir, string password, bool allowPackDirectory = true)
        {
            if (!File.Exists(fileToUnZip))
            {
                LogHelper.WriteErrorLogExt(taskId, "文件不存在{0}", fileToUnZip);
                return;
            }

            strUnpackDir = strUnpackDir.Replace("/", "\\");
            if (!strUnpackDir.EndsWith("\\"))
            {
                strUnpackDir += "\\";
            }

            if (!Directory.Exists(strUnpackDir))
            {
                Directory.CreateDirectory(strUnpackDir);
            }

            LogHelper.WriteInfoLogExt(taskId, "解压文件{0}到指定文件夹{1}", fileToUnZip, strUnpackDir);
            ZipInputStream s = null;
            ZipEntry theEntry = null;
            string fileName;
            try
            {
                s = new ZipInputStream(File.OpenRead(fileToUnZip));
                s.Password = password;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        fileName = Path.GetFileName(theEntry.Name);

                        if (directoryName != String.Empty)
                            Directory.CreateDirectory(strUnpackDir + directoryName);

                        fileName = Path.Combine(strUnpackDir, directoryName, theEntry.Name);
                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        //streamWriter = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
                        using (FileStream streamWriter = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            int size = 2048;
                            byte[] data = new byte[size];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                    streamWriter.Flush();
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        //streamWriter = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite,FileShare.ReadWrite);//2014-8-19 DXM 解决进程被占用 不能访问
                        //streamWriter.Close();
                    }
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteErrorLog(ex.ToString());
            }
            finally
            {               
                //if (streamWriter != null)
                //{
                //    streamWriter.Close();
                //    streamWriter.Dispose();
                //    streamWriter = null;
                //}
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);               
            }
        }

        #region 解压
        /// <summary> 
        /// 解压功能(解压压缩文件到指定目录) 
        /// </summary>
        /// <param name="logName"></param> 
        /// <param name="sourceZip">zip文件全路径</param> 
        /// <param name="targetFolder">解压输出目录</param> 
        /// <param name="password">解压密码</param>
        /// <param name="isPackDirectory">使用压缩包名做目录</param>
        /// <returns>是否成功</returns> 
        public static bool UnpackZipFile(string logName, string sourceZip, string targetFolder, string password = null, bool isPackDirectory = true)
        {
            //待解压文件校验
            if (string.IsNullOrEmpty(sourceZip) || !System.IO.File.Exists(sourceZip))
            {
                return false;
            }
            //解压文件格式判断
            string fileExt = Path.GetExtension(sourceZip);
            if (fileExt.ToLower().IndexOf("zip") <= 0)
            {
                return false;
            }

            if (isPackDirectory)
            {
                string packName = Path.GetFileNameWithoutExtension(sourceZip);
                targetFolder = Path.Combine(targetFolder, packName);
            }
            //输出目录校验
            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }
            //输出目录补全
            if (!targetFolder.EndsWith("\\"))
            {
                targetFolder += "\\";
            }
            LogHelper.WriteDebugLogExt(logName, "当前线程输入文件为{0}，输出目录为{1}", sourceZip, targetFolder);
            ZipEntry ent = null;
            using (var zipStream = new ZipInputStream(System.IO.File.OpenRead(sourceZip)))
            {
                if (!string.IsNullOrEmpty(password))
                {
                    zipStream.Password = password;
                }
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (ent.IsDirectory)
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(ent.Name))
                    {
                        continue;
                    }
                    string fileName = targetFolder + ent.Name.Replace('/', '\\');
                    var index = ent.Name.LastIndexOf('/');
                    if (index != -1)
                    {
                        string path = targetFolder + ent.Name.Substring(0, index).Replace('/', '\\');
                        System.IO.Directory.CreateDirectory(path);
                    }
                    var bytes = new byte[ent.Size];
                    zipStream.Read(bytes, 0, bytes.Length);
                    System.IO.File.WriteAllBytes(fileName, bytes);
                }
            }
            GC.Collect(1);
            return true;
        }
        #endregion

        private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string ParentFloderName)
        {
            bool res = true;
            string[] floders, filenames;
            ZipEntry entry = null;
            FileStream fs = null;
            //Crc32 crc = new Crc32();
            try
            {
                //创建当前文件夹
                entry = new ZipEntry(Path.Combine(ParentFloderName, Path.GetFileName(folderToZip) + "/"));
                //加“/”才会当成时文件夹创建
                s.PutNextEntry(entry);
                s.Flush();
                //先压缩文件，再递归压缩文件夹
                filenames = Directory.GetFiles(folderToZip);
                foreach (string file in filenames)
                {
                    //打开压缩文件
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(Path.Combine(ParentFloderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    //crc.Reset();
                    //crc.Update(buffer);
                    //entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            floders = Directory.GetDirectories(folderToZip);
            foreach (string folder in floders)
            {
                if (!ZipFileDictory(folder, s, Path.Combine(ParentFloderName, Path.GetFileName(folderToZip))))
                {
                    return false;
                }
            }
            return res;
        }

        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, string password)
        {
            bool res;
            if (!Directory.Exists(FolderToZip))
            {
                return false;
            }
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(6);
            s.Password = password;
            res = ZipFileDictory(FolderToZip, s, "");
            s.Flush();
            s.Close();
            return res;
        }

        private static bool ZipFile(string fileToZip, string ZipedFile, string Password)
        {
            if (!File.Exists(fileToZip))
            {
                throw new FileNotFoundException("指定要压缩的文件： " + fileToZip + " 不存在！");
            }
            FileStream zipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry zipentry = null;
            bool res = true;
            try
            {
                zipFile = File.OpenRead(fileToZip);
                byte[] buffer = new byte[zipFile.Length];
                zipFile.Read(buffer, 0, buffer.Length);
                zipFile.Close();
                zipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(zipFile);
                ZipStream.Password = Password;
                zipentry = new ZipEntry(Path.GetFileName(fileToZip));
                ZipStream.PutNextEntry(zipentry);
                ZipStream.SetLevel(6);
                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
                res = false;
            }
            finally
            {
                if (zipentry != null)
                {
                    zipentry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Flush();
                    ZipStream.Close();
                }
                if (zipFile != null)
                {
                    zipFile.Close();
                    zipFile = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return res;
        }

        /// <summary>
        /// 文件夹打包
        /// </summary>
        /// <param name="FileToZip">待打包文件夹</param>
        /// <param name="zipedFile">包文件名称</param>
        /// <param name="Password">包密码</param>
        /// <returns></returns>
        public static bool Zip(string FileToZip, string zipedFile, string Password)
        {
            if (Directory.Exists(FileToZip))
            {
                return ZipFileDictory(FileToZip, zipedFile, Password);
            }
            else if (File.Exists(FileToZip))
            {
                return ZipFile(FileToZip, zipedFile, Password);
            }
            else
            {
                return false;
            }
        }

        /// <summary>  
        /// tar包解压  
        /// </summary>  
        /// <param name="strFilePath">tar包路径</param>  
        /// <param name="strUnpackDir">解压到的目录</param>
        /// <param name="logName">日志输出文件名</param>  
        /// <returns></returns>  
        public static bool UnpackTarFiles(string strFilePath, string strUnpackDir, string logName)
        {
            try
            {
                //TO-DO: 需要测试本地解压移动到存储快还是直接在存储上解压快
                if (!File.Exists(strFilePath))
                {
                    LogHelper.WriteDebugLogExt(logName, "压缩包文件{0}不存在", strFilePath);
                    return false;
                }

                strUnpackDir = strUnpackDir.Replace("/", "\\\\");
                if (!strUnpackDir.EndsWith("\\\\"))
                {
                    strUnpackDir += "\\\\";
                }

                if (!Directory.Exists(strUnpackDir))
                {
                    Directory.CreateDirectory(strUnpackDir);
                }

                using (FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    ICSharpCode.SharpZipLib.Tar.TarInputStream s = new TarInputStream(fr);
                    TarEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);

                        if (directoryName != String.Empty)
                            Directory.CreateDirectory(strUnpackDir + directoryName);

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(strUnpackDir + theEntry.Name))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    s.Close();
                    //fr.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLogExt(logName, "压缩包文件{0}解压失败{1}", ex.ToString());
                return false;
            }
        }
    } 

}
